package common

import (
	"encoding/json"
	"financial_manual_server/util"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

// 静态访问
func StaticAccess(contextPath string, rootPath string) http.Handler {
	return http.StripPrefix(contextPath, http.FileServer(http.Dir(rootPath)))
}

type authVo struct {
	MerchantId     string `json:"merchantId"`     // 商户号
	MpAppId        string `json:"mpAppId"`        // 应用ID
	AppRedirectUrl string `json:"appRedirectUrl"` // 重定向地址
	State          string `json:"state"`          // 没什么用
	UserInfo       bool   `json:"userInfo"`       // 是否获取用户信息
	JsapiTicket    bool   `json:"jsapiTicket"`    // 不知道是啥
}

// 授权接口
func Auth(w http.ResponseWriter, r *http.Request) {
	config := util.GetConfig()
	vo := authVo{
		MerchantId:     config.WxWork.MerchantId,
		MpAppId:        config.WxWork.MpAppId,
		AppRedirectUrl: config.WxWork.AppRedirectUrl,
		State:          "test",
		UserInfo:       true,
		JsapiTicket:    false,
	}
	contentType := "application/json"
	body, _ := util.ToJson(vo)
	content := strings.NewReader(string(body))

	resp, err := http.Post(config.WxWork.Url+"fire-mps/UserAuthService/getUrl", contentType, content)
	if resp == nil || err != nil {
		body, _ = util.Fail("Resp is nil", nil)
	} else {
		defer resp.Body.Close()
		body, _ = ioutil.ReadAll(resp.Body)
		body, _ = util.Success(strings.Trim(string(body), "\""))
	}
	util.WriteJson(w, body)
}

type userBo2 struct {
	Id           string `json:"id"`
	IsAllowLogin bool   `json:"isAllowLogin"`
	UserCode     string `json:"userCode"`
	UserName     string `json:"userName"`
	UserType     string `json:"userType"`
	LineCode     string `json:"lineCode"`
}

type userBo2Resp struct {
	Code    int     `json:"code"`
	Message string  `json:"message"`
	Data    userBo2 `json:"data"`
}

// 检查用户权限
func CheckAccessible(w http.ResponseWriter, r *http.Request) {
	config := util.GetConfig()
	number := fmt.Sprintf("%08s", util.GetStringParam(r, "number"))

	// 超级授权，允许访问
	if strings.Contains(config.WxWork.Whitelist, number) {
		body, _ := util.Success("Super Auth")
		util.WriteJson(w, body)
		return
	}

	var body []byte
	resp, err := http.Get(config.WxWork.Url2 + "yfcloud-user/public/user/detailUserInfo?userCode=" + number)
	if resp == nil || err != nil {
		body, _ = util.Fail("Resp is nil", nil)
	} else {
		defer resp.Body.Close()
		res, _ := ioutil.ReadAll(resp.Body)

		// 仅财务战线员工可登录
		var userResp userBo2Resp
		err = json.Unmarshal(res, &userResp)
		if err != nil {
			body, _ = util.Fail("请求异常", err)
		} else if userResp.Code != 0 {
			body, _ = util.Fail("鉴权失败: "+userResp.Message, err)
		} else if userResp.Data.LineCode != "27" {
			body, _ = util.Fail("权限不足", err)
		} else {
			body, _ = util.Success("鉴权成功")
		}
	}
	util.WriteJson(w, body)
}

type userBo struct {
	UserId      string `json:"userid"`       // 工号
	Avatar      string `json:"avatar"`       // 高清头像
	ThumbAvatar string `json:"thumb_avatar"` // 小头像
	Name        string `json:"name"`         // 名称
	Mobile      string `json:"mobile"`       // 手机
	ErrCode     int    `json:"errcode"`      // 错误码，默认0
}

// 获取用户头像接口
func Avatar(w http.ResponseWriter, r *http.Request) {
	config := util.GetConfig()
	// 员工号
	uid := util.GetStringParam(r, "uid")
	contentType := "application/x-www-form-urlencoded"
	log.Println(uid)

	body := fmt.Sprintf("userId=%s&agentId=%s&type=%s", uid, config.WxUser.AgentId, config.WxUser.Type)
	resp, err := http.Post(config.WxUser.Url, contentType, strings.NewReader(body))

	if resp == nil || err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	defer resp.Body.Close()
	res, _ := ioutil.ReadAll(resp.Body)

	var user userBo
	err = json.Unmarshal(res, &user)
	if err != nil || user.ErrCode != 0 {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	log.Println("Thumb avatar", user.UserId, user.ThumbAvatar)
	http.Redirect(w, r, user.ThumbAvatar, http.StatusFound)
}
